package com.zhrenjie04.alex.manager.controller.outter.fore;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.UUID;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.zhrenjie04.alex.core.AuditLog;
import com.zhrenjie04.alex.core.FilterWithNoneFiltered;
import com.zhrenjie04.alex.core.Job;
import com.zhrenjie04.alex.core.JsonResult;
import com.zhrenjie04.alex.core.JsonResultSuccess;
import com.zhrenjie04.alex.core.Permission;
import com.zhrenjie04.alex.core.ResponseJsonBody;
import com.zhrenjie04.alex.core.User;
import com.zhrenjie04.alex.core.exception.PrerequisiteNotSatisfiedException;
import com.zhrenjie04.alex.core.interceptor.AuthorizationInterceptor;
import com.zhrenjie04.alex.manager.dao.UserDao;
import com.zhrenjie04.alex.manager.service.UserService;
import com.zhrenjie04.alex.util.JsonUtil;
import com.zhrenjie04.alex.util.Md5Util;
import com.zhrenjie04.alex.util.RedisUtil;
import com.zhrenjie04.alex.util.SessionUtil;

/**
 * @author 张人杰
 */
@Controller
@RequestMapping("/user/fore")
@Permission("fore")
public class UserForeLoginController {

	private static final Logger logger = Logger.getLogger(UserForeLoginController.class);

	@Autowired
	UserService userService;
	@Autowired
	UserDao userDao;
	@Value("${session.session-keep-time-seconds}")
	private int sessionKeepTimeSeconds = 10;

	@AuditLog(code = "login", memo = "登录操作")
	@RequestMapping(value = "/login/do-login", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@Permission("login.do-login")
	@ResponseJsonBody(type = User.class, include = "userId,username,realname,nickname,email,cellphone,portraitUrl,birthday,gender")
	public JsonResult login(@RequestBody User account, HttpServletResponse response) {
		HashMap<String, Object> params = new HashMap<String, Object>(16);
		params.put("username", account.getUsername());
		User user = userDao.queryObject(params);
		if (user == null) {
			throw new PrerequisiteNotSatisfiedException("该用户不存在");
			// 密码经过盐值加密判断：
		} else if (account.getPassword() != null && !"".equals(account.getPassword())
				&& Md5Util.encrypt(account.getPassword() + user.getSalt()).equals(user.getPassword())) {
			// 获取jobs列表
			user.setJobs(userService.queryJobs(user));
			// 指定第一个job
			if (user.getJobs() != null && !user.getJobs().isEmpty()) {
				Job job = user.getJobs().get(0);
				user.setCurrentJobId(job.getJobId());
				user.setPrivilegeCodes(userDao.queryUserPrivilegeCodes(job));
				user.setMenuLinks(userService.queryUserMenuLinks(job));
				user.setCurrentRoleIds(userDao.queryUserRoleIds(job));
			}
			String sid = "s-" + UUID.randomUUID();
			RedisUtil.set(sid, JsonUtil.stringify(user), sessionKeepTimeSeconds);
			String userSids = "user-sids-" + user.getUserId();
			RedisUtil.sadd(userSids, sessionKeepTimeSeconds, sid);
			JsonResult result = new JsonResultSuccess();
			result.put("authorization", sid);
			result.put("user", user);
			Cookie cookie = new Cookie(AuthorizationInterceptor.AUTHORIZATION_HEADER_KEY, sid);
			cookie.setPath("/");
			cookie.setMaxAge(-1);
			response.addCookie(cookie);
			return result;
		} else {
			throw new PrerequisiteNotSatisfiedException("密码错误");
		}
	}

	@RequestMapping(value = "/login/do-logout", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@Permission("login.do-logout")
	@ResponseJsonBody(type = FilterWithNoneFiltered.class)
	public JsonResult tree(HttpServletRequest request) {
		SessionUtil.killSession(request);
		return new JsonResultSuccess();
	}

	@RequestMapping(value = "/current-user", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@Permission("get-current-user")
	@ResponseJsonBody(type = User.class, include = "userId,username,realname,nickname,email,cellphone,portraitUrl,birthday,gender")
	public JsonResult getCurrentUser(HttpServletRequest request, HttpServletResponse response) {
		User user = SessionUtil.getSessionUser(request);
		JsonResult result = new JsonResultSuccess();
		result.put("user", user);
		result.put("sid", request.getAttribute("sid"));
		return result;
	}

	@RequestMapping(value = "/index", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@Permission("login.upload-file")
	public String index() {
		return "index";
	}

	@RequestMapping(value = "/login/upload-file", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@Permission("login.upload-file")
	@ResponseBody
	public JsonResult uploadFile(@RequestParam("imageFile") MultipartFile imageFile) {
		FileOutputStream fos = null;
		try {
			byte[] bytes = imageFile.getBytes();
			File file = new File("D:\\aaa.jpg");
			fos = new FileOutputStream(file);
			fos.write(bytes);
		} catch (IOException e) {
			logger.error(e);
		} finally {
			try {
				if (fos != null) {
					fos.close();
				}
			} catch (IOException e) {
				logger.error(e);
			}
		}
		return new JsonResultSuccess();
	}
}
